package com.hfb.io.bio;

import java.io.IOException;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * java SE 版 BIO ServerSocket
 *
 * 程序的问题：
 *  1、阻塞
 *  2、启动线程，提高并发——进而带来 C10K、C10M问题
 */
public class MyBIOServerSocket_02 {
    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = new ServerSocket(9000);
        while (true) {
            System.out.println("等待连接。。。");
            Socket clientSocket = serverSocket.accept(); // 阻塞方法
            System.out.println("客户端【" + clientSocket.getInetAddress() + "】连接了");
            new Thread(() -> {
                try {
                    handler(clientSocket);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }).start();
        }
    }
    private static void handler(Socket clientSocket) throws IOException {
        byte[] bytes = new byte[1024];
        System.out.println("准备read。。。");
        // 接收客户端的数据，阻塞方法，没有数据可读时就阻塞
        int read = clientSocket.getInputStream().read(bytes);
        System.out.println("read完毕。。。");
        if (read != -1) {
            System.out.println("接收客户端的数据：" + new String(bytes, 0, read));
        }
        OutputStream outputStream = clientSocket.getOutputStream();
        outputStream.write("HelloClient".getBytes());
        outputStream.flush();
    }
}
